import { radioChecked, searchCover, deepCopy, multipleChecked, getField, isString, isNumber, isArray } from "@/common.js"
// import { post } from "@/utils/network.js"
// 调整字段值
export const changeField = function (e, field) {
  e = e || ''
  const value = isString(e) || isNumber(e) || isArray(e) ? e : e.target.value
  // 更新当前条目值
  const item = {...this.item, [field]: value}
  this.$emit('setItem', item)
  // 更新整体表单的值
  let formData = searchCover(this.formData, {id: this.item.id}, v => ({...v, [field]: value}))
  formData = formData.map(v => ({...v, children: v.type == 'split' ? searchCover(v.children, {id: this.item.id}, v => ({...v, [field]: value})) : v.children}))
  this.$emit('setFormData', formData)
}
// 多选
export const checkedItem = function (optItem) {
  let options = multipleChecked(deepCopy(this.item.options), {id: optItem.id})
  const newState = !optItem.isChecked
  if(newState) {
    if(optItem.id == 1) {
      options = searchCover(options, {id: '1'}, v => v, v => ({...v, isChecked: false }))
    } else {
      options = searchCover(options, {id: '1'}, v => ({...v, isChecked: false}))
    }
  }
  const value1 = getField(options, 'id', v => v.isChecked).join(',')
  // 更新当前条目的值
  const item = {
    ...this.item,
    options, value1, 
    value2: optItem.id == 1 ? '' : this.item.value2,
    errmsg: value1 ? '' : this.item.errmsg
  }
  this.$emit('setItem', item)
  // 更新整体表单的值
  let formData = searchCover(this.formData, {id: this.item.id}, v => ({...v, options, value1, value2: optItem.id == 1 ? '' : v.value2, errmsg: value1 ? '' : v.errmsg }))
  formData = formData.map(v => ({...v, children: v.type == 'split' ? searchCover(v.children, {id: this.item.id}, v => ({...v, options, value1, value2: optItem.id == 1 ? '' : v.value2, errmsg: value1 ? '' : v.errmsg })) : v.children}))
  this.$emit('setFormData', formData)
  eval(this.item.onChange)(options.filter(v => v.isChecked))
}
// 获取单选的选项列表
export const getOptions = async function () {
  // if(!this.item.optionsUrl) { return false }
  // const options = await post(this.item.optionsUrl, {})
  // let formData = searchCover(this.formData, {id: this.item.id}, v => ({...v, options: options}))
  // formData = formData.map(v => ({...v, children: v.type == 'split' ? searchCover(v.children, {id: this.item.id}, v => ({...v, options: options})) : v.children}))
  // this.$emit('setFormData', formData)
}
// 调整其他症状
export const changeOther = function (e) {
  const value = isString(e) || isNumber(e) || isArray(e) ? e : e.target.value
  this.changeField(value, 'value2')
}